﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Windows;

namespace WPFChatClient
    
{
    public partial class MainWindow : Window
    {
        private MessageClient client;
        private LoginForm loginForm;
        private List<ChatWindow> groupChatWindows;
        private List<ForumWindow> forumChatWindows;
        private char SPLIT_CHAR;

        private String username;

        public MainWindow()
        {
            groupChatWindows = new List<ChatWindow>();
            forumChatWindows = new List<ForumWindow>();
            loginForm = new LoginForm(this);

            client = new MessageClient();
            SPLIT_CHAR = client.getSplitChar();

            client.updateGroupChat += client_updateGroupChat;

            client.confirmLogin += client_confirmLogin;
            client.rejectLogin += client_rejectLogin;
            client.showShutdownPopup += client_showShutdownPopup;

            client.promptChatroomListUpdate += client_updateChatroomList;
            client.promptUserListUpdate += client_updateUserList;
            client.promptForumTitlesUpdate += client_updateForumList;

            InitializeComponent();
            this.Hide();
        }

        internal MessageClient getMessageClient()
        {
            return this.client;
        }

        public void setServerAddress(String serverAddressString)
        {
            client.setServerAddress(serverAddressString);
        }

        public void loginClient(String _username)
        {
            this.username = _username;
            client.Start();

            if (!client.isRunning())
            {
                this.Hide();
                loginForm.showWarning("Server unreachable");
                loginForm.Show();
                return;
            }

            username = client.sanitiseUsername(username);
            client.requestLogin(username);
        }

        public void activateWindow()
        {
            Dispatcher.Invoke((Action)delegate{
                this.Title = "JCU Mailman - Logged in as " + username;
                this.Show();
                this.IsEnabled = true;
                userDropList.IsEnabled = false;
                forumPostList.IsEnabled = false;
                client.requestChatroomList();
                client.requestforumPostList();
            });
        }

        public void client_confirmLogin()
        {
            Dispatcher.Invoke((Action)delegate{
                loginForm.Hide();
                activateWindow();
            });
        }

        public void client_rejectLogin()
        {
            client.Stop();
            Dispatcher.Invoke((Action)delegate{
                this.Hide();
                loginForm.showWarning("Error logging in");
                loginForm.Show();
            });
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            this.Hide();
            loginForm.ShowDialog();
        }


        /** 
         * Create a new private chat window.
         */
        public void createGroupWindow(String chatroomName)
        {
            // Exit early if the window already exists.
            if (findGroupWindow(chatroomName) != -1)
                return;

            ChatWindow groupWindow = new ChatWindow(this, chatroomName);
            this.groupChatWindows.Add(groupWindow);

            //Thread chatroomThread = new Thread(() =>
            //{
                groupWindow.ShowDialog();

                // Remove the window from the active chat list after it has been closed.
                System.Diagnostics.Debug.WriteLine(groupChatWindows.ToString());
                groupChatWindows.Remove(groupWindow);
                System.Diagnostics.Debug.WriteLine(groupChatWindows.ToString());
                //groupChatWindows.RemoveAt(findGroupWindow(chatroomName));

            //});
            //chatroomThread.IsBackground = true;
            //chatroomThread.Start();
        }

        /** 
        * Create a new forum chat window.
        */
        public void createForumWindow(String forumWindowName)
        {
            // Exit early if the window already exists.
            if (findForumWindow(forumWindowName) != -1)
                return;

            ForumWindow forumWindow = new ForumWindow(this, forumWindowName);
            client.requestUserList();

            this.forumChatWindows.Add(forumWindow);

            //Thread chatroomThread = new Thread(() =>
            //{
                forumWindow.ShowDialog();

                // Remove the window from the active chat list after it has been closed.
                System.Diagnostics.Debug.WriteLine(forumChatWindows.ToString());
                forumChatWindows.Remove(forumWindow);
                System.Diagnostics.Debug.WriteLine(forumChatWindows.ToString());
                //groupChatWindows.RemoveAt(findGroupWindow(chatroomName));

            //});
            //chatroomThread.IsBackground = true;
            //chatroomThread.Start();
        }





        /**
         * Find the index of an open group chat window in the group chat window list.
         * @return The index of the group chat window. Index is -1 if not found.
         */
        private int findGroupWindow(string chatroomName)
        {
            for (int i = 0; i < groupChatWindows.Count; i++)
            {
                if (groupChatWindows[i].getName().Equals(chatroomName))
                    return i;
            }
            return -1;
        }

        /**
       * Find the index of an open forum chat window in the forum chat window list.
       * @return The index of the forum chat window. Index is -1 if not found.
       */
        private int findForumWindow(string forumWindowName)
        {
            for (int i = 0; i < forumChatWindows.Count; i++)
            {
                if (forumChatWindows[i].Name.Equals(forumWindowName))
                    return i;
            }
            return -1;
        }



        public void client_updateGroupChat(String destination, String message)
        {
            int windowNumber = findGroupWindow(destination);
            if (windowNumber >= 0)
            {
                groupChatWindows[windowNumber].appendChatLine(message);
            }
        }

        public void client_updateChatroomList()
        {
            Dispatcher.Invoke((Action)delegate
            {
                userDropList.IsEnabled = true;
                userDropList.ItemsSource = client.getChatroomList();
                userDropList.UpdateLayout();
            });

        }

        public void client_updateForumList()
        {
            Dispatcher.Invoke((Action)delegate{
                forumPostList.IsEnabled = true;
                forumPostList.ItemsSource = client.getForumPostList();
                forumPostList.UpdateLayout();
            });

        }



        public void client_updateUserList()
        {
            Dispatcher.Invoke((Action)delegate{
                System.Diagnostics.Debug.WriteLine("FUCKADAY");
                foreach (ForumWindow forum in forumChatWindows)
                {
                    forum.updateUserList(client.getUserList());
                }

            });

        }


        /**
         * Create a new chat window for the selected chat room.
         */
        private void privateChatBtn_Click(object sender, EventArgs e)
        {
            try
            {
                String chatroomName = userDropList.SelectedItem.ToString();
                createGroupWindow(chatroomName);
                System.Diagnostics.Debug.WriteLine("new window: " + chatroomName);
            }
            catch (NullReferenceException ex)
            { }
        }

       
        /**
         * Show a popup dialog box containing a shutdown message from the server.
         * The client will close after the message has been confirmed.
         */
        public void client_showShutdownPopup(String shutdownMessage)
        {
            const string caption = "Client Disconnected";
            var result = MessageBox.Show(shutdownMessage, caption, MessageBoxButton.OK, MessageBoxImage.Error);

            Dispatcher.Invoke((Action)delegate{
             this.Close(); });
        }

        /**
          * Create a new forum window for the selected post.
          */

        private void ForumButton_Click(object sender, EventArgs e)
        {
            try
            {
                String forumPostName = userDropList.SelectedItem.ToString();
                createForumWindow(forumPostName);
                System.Diagnostics.Debug.WriteLine("new window: " + forumPostName);
            }
            catch (NullReferenceException ex)
            { }
        }

        /**
                * Create a new forum window for a new post.
                */

        private void NewPostButton_Click(object sender, EventArgs e)
        {
            try
            {
                String NewPostName = "";
                createForumWindow(NewPostName);
                System.Diagnostics.Debug.WriteLine("new window: " + NewPostName);
            }
            catch (NullReferenceException ex)
            { }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            client.Stop();
        }


    }
 
}
